<template>
    <!--    搜索条件框-->
    <div class="cardContent">
        <a-form
                ref="formRef"
                layout="inline"
                :model="searchData">
            <a-form-item label="关键词">
                <a-input v-model:value="searchData.keyword" placeholder="请输入关键词"></a-input>
            </a-form-item>
            <a-form-item label="状态">
                <a-select v-model:value="searchData.status" placeholder="请选择状态">
                    <a-select-option :value="null">全部</a-select-option>
                    <a-select-option :value="0">正常</a-select-option>
                    <a-select-option :value="1">下架</a-select-option>
                </a-select>
            </a-form-item>
            <a-space>
                <a-button type="primary" @click="load(1)">搜索</a-button>
                <a-button type="default" @click="reset">重置</a-button>
            </a-space>
        </a-form>
    </div>
    <!--    列表展示-->
    <div class="cardContent">
        <a-button type="primary" @click="openModal({},'产品上架')">产品上架</a-button>
        <a-table :dataSource="productList"
                 style="margin-top: 10px"
                 :columns="columns"
                 :pagination="false"
                 size="small"
                 bordered>
            <template #bodyCell="{text,record,index,column}">
                <template v-if="column.key == 'status'">
                    {{text == 0 ? '正常' : '下架'}}
                </template>
                <template v-if="column.key == 'discount'">
                    {{text * 100}}%
                </template>
                <template v-if="column.key == 'pic'">
                    <a-image
                            :src="text"
                            style="width: 32px;height: 32px"></a-image>
                </template>
                <a-space v-if="column.key == 'action'">
                    <a-button type="primary" @click="openModal(record,'详情')">详情</a-button>
                    <a-popconfirm
                            title="是否确认删除?"
                            ok-text="是"
                            cancel-text="否"
                            @confirm="okDelete(record.id)"
                    >
                        <a-button type="danger">删除</a-button>
                    </a-popconfirm>
                </a-space>
            </template>
        </a-table>
        <a-config-provider :locale="locale">
            <a-pagination style="margin-top: 10px; text-align: right"
                          v-model:current="pagination.current"
                          v-model:pageSize="pagination.pageSize"
                          show-quick-jumper
                          show-size-changer
                          :total="pagination.total"
                          :show-total="total => `总 ${total} 条数据`"
                          :page-size-options="pageSizeOptions"
                          @change="onChange"/>
        </a-config-provider>
    </div>
    <a-drawer
            v-model:visible="visible"
            width="800"
            :title="drawerTitle"
            placement="right"
            :footer-style="{textAlign: 'right'}"
    >
        <a-form :model="product" layout="vertical">
            <a-row :gutter="16" v-if="drawerTitle == '产品上架'">
                <a-col :span="12">
                    <a-form-item label="待上架的概念产品" v-bind="validateInfos.conceptualId">
                        <a-select :options="conceptualProductList"
                                  :field-names="{label: 'title',value: 'id'}"
                                  placeholder="请选择概念产品"
                                  @change="selectedConceptual"
                                  v-model:value="product.conceptualId"/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item label="产品名称" v-bind="validateInfos.name">
                        <a-input v-model:value="product.name"/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="8">
                    <a-form-item label="研发成品图" v-bind="validateInfos.pic">
                        <upload v-model:imgUrl="product.pic"
                                :upload-url="'http://47.113.223.105:8088/upload'"/>
                    </a-form-item>
                </a-col>
                <a-col :span="16">
                    <a-form-item label="卖点">
                        <a-textarea v-model:value="product.sellPoint" :rows="4"/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="8">
                    <a-form-item label="价格" v-bind="validateInfos.price">
                        <a-input-number addon-after="￥" v-model:value="product.price" :min="minPrice"/>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="库存">
                        <a-input-number addon-after="件" v-model:value="product.num" :disabled="true"/>
                    </a-form-item>
                </a-col>
                <a-col :span="8">
                    <a-form-item label="最小交易量" v-bind="validateInfos.minTradingVolume">
                        <a-input-number addon-after="件" v-model:value="product.minTradingVolume"/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="8">
                    <a-form-item label="折扣">
                        <a-slider v-model:value="product.discount"
                                  :tip-formatter="val => Number(val * 100).toFixed(0) + '%'"
                                  :min="0"
                                  :max="1"
                                  :step="0.01"/>
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item label="状态">
                        <a-switch v-model:checked="product.status"
                                  :checked-value="0"
                                  :un-checked-value="1"
                                  checked-children="正常"
                                  un-checked-children="下架"/>
                    </a-form-item>
                </a-col>
            </a-row>
            <a-row :gutter="16">
                <a-col :span="24">
                    <a-form-item label="产品描述">
                        <div style="border: 1px solid #ccc">
                            <Toolbar
                                    style="border-bottom: 1px solid #ccc"
                                    :editor="editorRef"
                                    :defaultConfig="toolbarConfig"
                                    :mode="mode"
                            />
                            <Editor
                                    style="height: 500px; overflow-y: hidden;"
                                    v-model="product.description"
                                    :defaultConfig="editorConfig"
                                    :mode="mode"
                                    @onCreated="handleCreated"
                            />
                        </div>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
        <template #footer>
            <a-space>
                <a-button type="default" @click="visible = false">取消</a-button>
                <a-button type="primary" @click="saveOrUpdate">保存</a-button>
            </a-space>
        </template>
    </a-drawer>
</template>

<script>
    import zhCN from "ant-design-vue/lib/locale-provider/zh_CN";
    import axios from "axios";
    import {Form, message} from "ant-design-vue";
    import upload from '@/components/upload'
    import '@wangeditor/editor/dist/css/style.css' // 引入 css
    import {onBeforeUnmount, ref, shallowRef, onMounted} from 'vue'
    import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

    export default {
        name: "productList",
        components: {
            upload,
            Editor,
            Toolbar
        },
        setup() {
            const columns = [
                {
                    title: 'ID',
                    dataIndex: 'id',
                    key: 'id',
                },
                {
                    title: '产品名称',
                    dataIndex: 'name',
                    key: 'name',
                },
                {
                    title: '图片',
                    dataIndex: 'pic',
                    key: 'pic',
                },
                {
                    title: '单价',
                    dataIndex: 'price',
                    key: 'price',
                },
                {
                    title: '库存',
                    dataIndex: 'num',
                    key: 'num',
                },
                {
                    title: '状态',
                    dataIndex: 'status',
                    key: 'status',
                },
                {
                    title: '折扣',
                    dataIndex: 'discount',
                    key: 'discount',
                },
                {
                    title: '最小交易量',
                    dataIndex: 'minTradingVolume',
                    key: 'minTradingVolume',
                },
                {
                    title: '操作',
                    key: 'action',
                    align: 'center',
                    width: '200px'
                }
            ]
            const locale = zhCN
            const product = ref({
                conceptualId: undefined,
                name: '',
                pic: '',
                price: undefined,
                minTradingVolume: undefined,
            })
            const productList = ref()
            const conceptualProductList = ref()
            const searchData = ref({})
            const pagination = ref({
                current: 1,
                pageSize: 5,
            })
            const pageSizeOptions = ref(['5', '10', '20', '30', '50', '100'])
            const visible = ref(false);
            const drawerTitle = ref('');
            const minPrice = ref();

            const useForm = Form.useForm
            const {validate, validateInfos, resetFields, validateField, rulesRef} = useForm(product, ref({
                conceptualId: [{required: true, message: '请选择概念产品', trigger: ['change']}],
                name: [{required: true, message: '请输入产品名名', trigger: ['change']}],
                pic: [{required: true, message: '请上传头像', trigger: ['change']}],
                price: [{required: true, message: '请输入产品价格', trigger: ['change']}],
                minTradingVolume: [{required: true, message: '最小交易量不能为空', trigger: ['change']}],
            }))

            const saveOrUpdate = () => {
                validate().then(() => {
                    console.log("通过校验")
                    axios.post('/product/saveOrUpdate', product.value).then(rs => {
                        console.log("新增或修改结果：", rs)
                        if (rs.code == 200) {
                            visible.value = false
                            message.success("操作成功")
                            load()
                        } else {
                            message.error(rs.message)
                        }
                    })
                }).catch(() => {
                    console.log("校验失败")
                })

            }

            const okDelete = (id) => {
                console.log("要删除的ID：" + id)
                axios.delete('/product/deleteById/' + id).then(rs => {
                    if (rs.code == 200) {
                        message.success("删除成功")
                        load()
                    } else {
                        message.error(rs.message)
                    }
                })
            }

            const openModal = (obj, message) => {
                console.log("模态框参数：", obj)
                drawerTitle.value = message
                product.value = JSON.parse(JSON.stringify(obj))
                if (message == '产品上架') {
                    resetFields()
                    product.value.status = 0
                    product.value.discount = 1
                    product.value.num = 0
                    axios.get('conceptual/queryDeveloped').then(rs => {
                        console.log("获取成功研发产品详情：" + rs)
                        conceptualProductList.value = rs.data
                        visible.value = true;
                    })
                } else {
                    visible.value = true;
                }
            }

            const selectedConceptual = (val, option) => {
                // console.log("value:", val)
                // console.log("option:", option)
                product.value.price = option.productionCosts
                minPrice.value = option.productionCosts
                product.value.pic = option.pic
                product.value.name = option.title
            }

            const load = (pageNum) => {
                pagination.value.current = pageNum == 1 ? 1 : pagination.value.current
                axios.get('/product/queryByCondition', {
                    params: {
                        pageNum: pagination.value.current,
                        pageSize: pagination.value.pageSize,
                        keyword: searchData.value.keyword,
                        status: searchData.value.status
                    }
                }).then(rs => {
                    console.log("查找结果：", rs)
                    productList.value = rs.data.records
                    pagination.value.total = rs.data.total
                })
            }

            const onChange = (pageNum, pageSize) => {
                pagination.value.current = pageNum
                pagination.value.pageSize = pageSize
                load()
            }

            const reset = () => {
                searchData.value = {}
                load()
            }

            // 编辑器实例，必须用 shallowRef
            const editorRef = shallowRef()
            const toolbarConfig = {}
            const editorConfig = {
                placeholder: '请输入内容...',
                MENU_CONF: {}
            }

            editorConfig.MENU_CONF['uploadImage'] = {
                server: 'http://localhost:8088/uploadPic',
                // form-data fieldName ，默认值 'wangeditor-uploaded-image'
                fieldName: 'file',

                // 单个文件的最大体积限制，默认为 2M
                maxFileSize: 5 * 1024 * 1024, // 5M

                // 最多可上传几个文件，默认为 100
                maxNumberOfFiles: 10,

                // 选择文件时的类型限制，默认为 ['image/*'] 。如不想限制，则设置为 []
                allowedFileTypes: ['image/*'],

                // 自定义上传参数，例如传递验证的 token 等。参数会被添加到 formData 中，一起上传到服务端。
                // meta: {
                //     token: 'xxx',
                //     otherKey: 'yyy'
                // },

                // 将 meta 拼接到 url 参数中，默认 false
                // metaWithUrl: false,

                // 自定义增加 http  header
                // headers: {
                //     Accept: 'text/x-json',
                //     otherKey: 'xxx'
                // },

                // 跨域是否传递 cookie ，默认为 false
                withCredentials: true,

                // 超时时间，默认为 10 秒
                timeout: 5 * 1000, // 5 秒

                // 上传之前触发
                // onBeforeUpload(file: File) { // TS 语法
                onBeforeUpload(file) {    // JS 语法
                    // file 选中的文件，格式如 { key: file }
                    return file

                    // 可以 return
                    // 1. return file 或者 new 一个 file ，接下来将上传
                    // 2. return false ，不上传这个 file
                },

                // 上传进度的回调函数
                // onProgress(progress: number) {  // TS 语法
                onProgress(progress) {       // JS 语法
                    // progress 是 0-100 的数字
                    console.log('progress', progress)
                },

                // 单个文件上传成功之后
                // onSuccess(file: File, res: any) {  // TS 语法
                onSuccess(file, res) {          // JS 语法
                    console.log(`${file.name} 上传成功`, res)
                },

                // 单个文件上传失败
                // onFailed(file: File, res: any) {   // TS 语法
                onFailed(file, res) {           // JS 语法
                    console.log(`${file.name} 上传失败`, res)
                },

                // 上传错误，或者触发 timeout 超时
                // onError(file: File, err: any, res: any) {  // TS 语法
                onError(file, err, res) {               // JS 语法
                    console.log(`${file.name} 上传出错`, err, res)
                },
            }

            // 组件销毁时，也及时销毁编辑器
            onBeforeUnmount(() => {
                const editor = editorRef.value
                if (editor == null) return
                editor.destroy()
            })

            const handleCreated = (editor) => {
                editorRef.value = editor // 记录 editor 实例，重要！
            }


            onMounted(() => {
                load()
            })
            return {
                columns,
                product,
                productList,
                pagination,
                pageSizeOptions,
                onChange,
                load,
                locale,
                searchData,
                reset,
                visible,
                openModal,
                saveOrUpdate,
                okDelete,
                conceptualProductList,
                drawerTitle,
                selectedConceptual,
                editorRef,
                mode: 'default', // 或 'simple'
                toolbarConfig,
                editorConfig,
                handleCreated,
                minPrice,
                validateInfos,
            }
        }
    }
</script>

<style scoped>
    .cardContent {
        background: #fff;
        margin: 10px 10px 0 10px;
        padding: 15px;
    }
</style>